package logic

import (
	"context"
	"fmt"
	"my-zero-tiktok/apps/comment/models"
	"my-zero-tiktok/common/constant"
	"my-zero-tiktok/common/xerr"

	"my-zero-tiktok/apps/comment/pb/pb"
	"my-zero-tiktok/apps/comment/rpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddCommentLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddCommentLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddCommentLogic {
	return &AddCommentLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// AddComment 新增评论
func (l *AddCommentLogic) AddComment(in *pb.AddCommentRequest) (*pb.Empty, error) {
	result, err := l.svcCtx.CommentModel.Insert(l.ctx, &models.Comment{
		UserId:  in.UserId,
		VideoId: in.VideoId,
		Content: in.Content,
	})
	if err != nil {
		return nil, xerr.DBError()
	}

	commentID, err := result.LastInsertId()
	if err != nil {
		return nil, xerr.DBError()
	}

	comScore := constant.VideoComWeight*0 + constant.VideoFavComWeight*0 + constant.VideoComWeight*commentID
	comVideoKey := fmt.Sprintf("%s:%d", constant.ComVideoKey, in.VideoId)
	_, _ = l.svcCtx.Redis.ZaddCtx(l.ctx, comVideoKey, int64(comScore), fmt.Sprintf("%d", commentID))
	return &pb.Empty{}, nil
}
